import { RequestInterceptors, type InternalAxiosRequestCustomConfig, type AxiosCustomError } from './type';
import axios from 'axios';
import AxiosMax from './Axios';
import { retry } from './axiosRetry';
import { checkErrorStatus } from './checkErrorStatus';
import staticAxiosConfig from './config';
import { hasCache, setCache, rejectRequestToCached } from './axiosCache';

export enum ContentTypeEnum {
	// json
	JSON = 'application/json;charset=UTF-8',
	// form-data qs
	FORM_URLENCODED = 'application/x-www-form-urlencoded;charset=UTF-8',
	// form-data  upload
	FORM_DATA = 'multipart/form-data;charset=UTF-8',
}

const _RequestInterceptors: RequestInterceptors = {
	// transformRequest
	// transformResponse
	requestInterceptors: async (config) => {
		// 添加token
		// const token = localStorage.getItem('token');
		// if (token) {
		//     config.headers.Authorization = `Bearer ${token}`;
		// }
		await hasCache(config);
		return config;
	},

	requestInterceptorsCatch: (err) => {
		return err;
	},
	responseInterceptor: (res) => {
		// status === 200, code !== 200 看接口定义
		// 只有成功的请求才缓存, 这里需要根据自己的业务来处理
		if (res.status === 200 && res.data.code === 200) {
			setCache(res.config, res.data);
		}
		// res.status === 200 && res.data.code !== 200 message 提示自行处理
		return res.data;
	},
	responseInterceptorsCatch(axiosInstance, err: AxiosCustomError) {
		const message = err.code === 'ECONNABORTED' ? '请求超时' : '请求失败';
		// 如果取消了上一次的请求，则返回true
		if (axios.isCancel(err)) {
			// @ts-ignore cache
			if (err.config?.cache) {
				return rejectRequestToCached(err);
			}
			return Promise.reject(err);
		}
		if (!((err as AxiosCustomError).config as InternalAxiosRequestCustomConfig)?.retry) {
			checkErrorStatus((err as AxiosCustomError).response?.status, message, (message) => console.log(message));
			return Promise.reject(err);
		}
		return retry(axiosInstance, err as AxiosCustomError);
	},
};

const useRequest = new AxiosMax({
	baseURL: staticAxiosConfig.baseUrl,
	headers: { 'Content-Type': ContentTypeEnum.JSON },
	// directlyGetData: true, res.data || res
	timeout: 10000,
	interceptors: _RequestInterceptors,
	abortRepetitiveRequest: true, // 是否支持取消
	cache: false, // 默认不缓存
	retry: true,
	retryConfig: {
		count: 3,
		waitTime: 500,
	},
});

export default useRequest;
